package com.yanjr.modules.sys.dao.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.yanjr.common.Constants;
import com.yanjr.common.persistence.BaseDaoImpl;
import com.yanjr.modules.sys.dao.UserDao;
import com.yanjr.modules.sys.entity.User;

@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

	@Override
	public List<User> findAllList() {
		String sql = "select * from sys_user where del_flag=? order by create_date desc";
		return super.findList(sql, new Object[] {Constants.DEL_FLAG_NORMAL});
	}
	
	@Override
	public List<User> findByRoleId(String orleId) {
		String sql = "select u.*, o1.name companyName, o2.name officeName from sys_user u join sys_user_role ur on u.id=ur.user_id "
				+ "left join sys_office o1 on (u.company_id=o1.id and o1.type='1' and o1.del_flag='0') "
				+ "left join sys_office o2 on (u.office_id=o2.id and o1.type='1' and o1.del_flag='0') "
				+ "where u.del_flag=? and ur.role_id=?";
		return super.findList(sql, new Object[] {Constants.DEL_FLAG_NORMAL, orleId});
	}

	@Override
	public User findByLoginName(String loginName) {
		String sql = "select u.*, o1.name companyName, o2.name officeName from sys_user u "
				+ "left join sys_office o1 on (u.company_id=o1.id and o1.type='1' and o1.del_flag='0') "
				+ "left join sys_office o2 on (u.office_id=o2.id and o1.type='1' and o1.del_flag='0') "
				+ "where u.del_flag=? and u.login_name=?";
		return super.findOne(sql, new Object[] {Constants.DEL_FLAG_NORMAL, loginName});
	}

	@Override
	public int updatePasswordById(String newPassword, String id) {
		String sql = "update sys_user set password=? where id=?";
		return super.update(sql, new Object[] {newPassword, id});
	}

	@Override
	public int updateLoginInfo(String loginIp, Date loginDate, String id) {
		String sql = "update sys_user set login_ip=?, login_date=? where id=?";
		return super.update(sql, new Object[] {loginIp, loginDate, id});
	}

	@Override
	public User getUser(String id) {
		String sql = "select u.*, o1.name companyName, o2.name officeName "
				+ "from sys_user u join sys_office o1 on (u.company_id=o1.id and o1.type='1' and o1.del_flag='0') "
				+ "join sys_office o2 on (u.office_id=o2.id and o1.type='1' and o1.del_flag='0') "
				+ "where u.del_flag=? and u.id=?";
		return super.findOne(sql, new Object[] {Constants.DEL_FLAG_NORMAL, id});
	}

}
